import React, { useState, useEffect } from 'react';
import { Button, Divider, List, Pagination, Icon, Popconfirm } from 'antd';
import { useHistory } from 'react-router-dom';
// import mainpage_bg_mobile from '../../../img/kc/mobile_form.jpg'
import {
  openNotification_util, checkdatavalid_util_formdata, fetchsync_util,
  resultdata_to_formdata, convertISODateTimeToYYYYMMDDHHMM,convertISODateTimeToYYYYMMDD,
  use_olreport_bybbbm,
  getCurrentDate_util,
  usenowDate,use_dict_byzdmc
} from '../util/util.js'
import Customfielditem_hook_mobile from '../newmes/customfielditem_hook_mobile.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { SaveOutlined } from '@ant-design/icons';
import { use_bgd_mx_initformdata } from './use_mobile_config.js';
import mainpage_bg from '../../../img/shipSRM/mobile_top.png'

moment.locale('zh-cn')
var storage = window.localStorage;

const Mobile_cprk_form = () => {
  const history = useHistory();
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    datas_wl: [],
    datas_gx: [],
    datas_gylx: [],
    datas_cj: [],
  })
  //请购单明细
  const [mxdata, setmxdata] = useState([])
  const [nowData, setNowData] = useState([])
  const [delidarr, setDelidarr] = useState([]);
  const [total, setTotal] = useState(0)
  const [current, setCurrent] = useState(1)
  const [pagesize, setPageSize] = useState(5)
  const [mxIndex, setMxIndex] = useState()
  const [addIndex, setAddIndex] = useState(1)
  //表单数据
  const [formdata, setformdata] = useState(use_bgd_mx_initformdata)
  

  //登出
  const handlelogout = () => {
    history.push({ pathname: '/shipSRM_mobile/cgrk/mobile_bgd_list' });
  }

  //去首页
  const handletomainpage = () => {
    history.push({ pathname: '/shipSRM_mobile/mobile_mainpage' });
  }

    // 页面进入加载数据
  useEffect(() => {
    JSON.parse(storage.preitem_bgd).type == "add" ? initdatasource() :
    init(JSON.parse(storage.preitem_bgd).data.id)
  }, [])

  //初始化
  const init = async (id) => {
    console.log(id,"0--")
    let rtdata = await fetchsync_util("/admin/scgl/query_bgd_byid", 'POST', { id }, "json")

    let newformdata = formdata
    newformdata.bgsj.value = convertISODateTimeToYYYYMMDD(rtdata.resultdata.formdata.bgsj)
    newformdata.djh.value = rtdata.resultdata.formdata.djh
    newformdata.bz.value = rtdata.resultdata.formdata.bz
    newformdata.sscj.value = rtdata.resultdata.formdata.sscj
    newformdata.create_by.value = rtdata.resultdata.formdata.create_by
    let mxdata = rtdata.resultdata.mxdata
    setformdata({ ...newformdata })
    setmxdata(mxdata)
    initdatasource()
    let nowData = mxdata.slice((current - 1) * pagesize, current * pagesize)
    setNowData(nowData)
  }


  /**
  * 初始化数据仓库
  */
  const initdatasource = async () => {
    //在线报表
    var cusqueryobj = await use_olreport_bybbbm(['query_wl','query_gy','query_gylx'])
    var dictobj = await use_dict_byzdmc(['dict_cj'])
    dynDatasObject.datas_wl = cusqueryobj.query_wl
    dynDatasObject.datas_gx = cusqueryobj.query_gy
    dynDatasObject.datas_gylx = cusqueryobj.query_gylx
    dynDatasObject.datas_cj = dictobj.dict_cj
    setdynDatasObject({ ...dynDatasObject })
  }

  const onShowSizeChange = (page) => {
    let nowData = mxdata.slice((page - 1) * pagesize, page * pagesize)
    setNowData(nowData)
    setCurrent(page)
  }


  //设置value
  const setfield = (onekey, value, settype) => {
    if (settype == 'single') {
      var newitem = formdata[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
      setformdata(newformdata)
    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }

  const deleteMx = (item) => {
    let newmxdata = mxdata.filter(item2 => item2.id != item.id).map((item3, index) => {
      item3.index = index
      return item3
    })
    delidarr.push(item.id)
    setDelidarr(delidarr)
    setmxdata(newmxdata)
    let nowData = newmxdata.slice((current - 1) * pagesize, current * pagesize)
    setNowData(nowData)
  }

  const hanldeadd = async () => {
    var checkobj = checkdatavalid_util_formdata(formdata)
    //主表字段校验没通过不能保存，目前没写子表校验。
    
    if (!checkobj.rtstatus) { openNotification_util(checkobj.rtmessage);return; }
    let newmxdata={}
    for(var item in formdata){
      newmxdata[item] = formdata[item].value
    }
    mxdata.push(newmxdata)
    setAddIndex(addIndex + 1)
    setmxdata(mxdata)
    clean()
    setNowData(mxdata)
  }

  const clean = () => {
    let cj =formdata.sscj.value
    let bz = formdata.bz.value
    for(var item in formdata){
      formdata[item].value = ""
    }
    formdata.create_by.value = storage.ygxm
    formdata.bgsj.value = getCurrentDate_util(1)
    formdata.sscj.value = cj
    formdata.bz.value = bz
    formdata.create_time.value = usenowDate()
    setformdata({ ...formdata })
  }

  const handleupload = async () => {
    var zsl =0
    mxdata.forEach(item => {
      zsl += item.bgsl
    })
    // var checkobj = checkdatavalid_util_formdata(formdata)
    // //主表字段校验没通过不能保存，目前没写子表校验。
    // openNotification_util(checkobj.rtmessage);
    // if (!checkobj.rtstatus) { return; }
    // else;
    //设置submit url
    let rtdata
    if (JSON.parse(storage.preitem_bgd).type == "add") {
      rtdata = await fetchsync_util("/admin/scgl/add_bgd_mx", 'POST', { mxdata,storage, formdata,zsl }, "json")
    }
    // } else {
    //   rtdata = await fetchsync_util("/admin/cggl/update_bgd_mx", 'POST', { mainid: JSON.parse(storage.preitem_bgd).data.id, mxdata, delidarr }, "json")
    // }
    openNotification_util(rtdata.rtmessage)
    if (JSON.parse(storage.preitem_bgd).type == "add") {
      history.push({ pathname: '/shipSRM_mobile/cgrk/mobile_bgd_list' })
    }
  }
  


  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook_mobile form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook_mobile form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={{ height: "100vh", width: "100%", position: 'relative', backgroundColor: "white" }}>
      {/* 首页  */}
      <div style={{
          width: "100%", height: "38vw",
          backgroundImage: `url(${mainpage_bg})`,
          position: "relative", fontSize: "0.9rem",
          textIndent: "2rem", fontWeight: "500", color: "white", borderRadius: "0 0 15px 15px"
        }} >
        <br />&nbsp;&nbsp;&nbsp;&nbsp;生产报工
        <Button type="primary" style={{ backgroundColor: "rgba(0,0,0,0.1)", height: "18%", position: "absolute", right: "1%", top: "5%", textAlign: "center" }}
          onClick={handlelogout}>
          列表
        </Button>
        <Button type="primary" style={{ backgroundColor: "rgba(0,0,0,0.1)", height: "18%", position: "absolute", right: "18%", top: "5%", textAlign: "center" }}
          onClick={handletomainpage}>
          首页
        </Button>
      </div>

      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap",
        }}>
          {renderfileditem()}
        </div>


        {JSON.parse(storage.preitem_bgd).type === "add"?(<div style={{ width: "100%", position: "absolute", }} >

          <Button type="primary" onClick={() => { hanldeadd() }}
            style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.6rem", left: "1rem", position: "absolute" }}>
            <SaveOutlined />{"新增"}</Button>
        </div>):<></>}
        {/* 主表区域结束 */}
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <Divider></Divider>

        <div style={{ ...styles.linestyle, marginTop: '-5vw' }} >
          <div style={styles.lineleft}><a style={{ color: "red" }}></a>&nbsp;生产报工明细</div>
        </div>

        <div style={{ width: "90vw", height: "", backgroundColor: "#FFFFFF", marginLeft: "5vw" }}>
          <List
            itemLayout="horizontal"
            dataSource={nowData}
            renderItem={(item, index) => (

              <div style={{
                width: "100%", backgroundColor: "white", marginTop: "5px", position: "relative",
                fontWeight: "400", fontSize: "0.6rem", borderRadius: "5px", overflow: "hidden", textAlign: 'left', lineHeight: "1.2rem",
                borderStyle: "solid", borderWidth: "0.05rem", borderColor: "#B8B8B8"
              }}>
                <div style={{ width: "100%", height: "0.8rem", position: "relative", marginTop: "0.5rem" }}>
                  <div style={{ color:"#377AF6",width: "90%", height: "100%",fontSize: "0.7rem", position: "absolute", left: "0", top: "0", textAlign: "left", fontWeight: "600" }}>
                    &nbsp;&nbsp;序号：{index + 1}</div>
                </div>
                {/* <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "90%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;检验编号：{JSON.parse(storage.preitem_bgd).data.jybh}</div>
                </div> */}

                <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "90%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;成品物料名称：{item.wlmc}</div>
                </div>
                {/* <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "70%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;成品物料编码：{item.wlbm}&nbsp;&nbsp;</div>
                </div> */}
                <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "70%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;规格型号：{item.ggxh}&nbsp;&nbsp;</div>
                </div>
                {/* <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "70%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;金蝶编码：{item.jdbm}&nbsp;&nbsp;</div>
                </div> */}
                <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "50%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;单位：{item.dw}</div>
                  <div style={{ width: "50%", height: "100%", position: "absolute", right: "0", top: "0", textAlign: "left" }}>
                    报工数量：{item.bgsl}&nbsp;&nbsp;</div>
                </div>
                {/* <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "50%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;工序：{item.gx}</div>
                  <div style={{ width: "50%", height: "100%", position: "absolute", right: "0", top: "0", textAlign: "left" }}>
                    工艺路线：{item.gylx}&nbsp;&nbsp;</div>
                </div> */}
                <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "70%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;工艺：{item.gx}&nbsp;&nbsp;</div>
                </div>
                {JSON.parse(storage.preitem_bgd).type === "add"?(<div style={{
                  width: "100%", backgroundColor: "white", fontWeight: "400", lineHeight: "0.8rem",
                  wordWrap: "break-word", textIndent: "0", margin: "5px",
                }}>
                  <Popconfirm
                    title="删除"
                    description="是否确实删除此检验?"
                    onConfirm={() => deleteMx(item)}
                    okText="删除"
                    cancelText="取消"
                  >
                    <Button
                      type="primary" style={{ height: "1.2rem", fontSize: "0.55rem", position: "relative" }}>删除</Button>
                  </Popconfirm>
                </div>):<div style={{
                  width: "100%", margin: "5px",}}></div>}
              </div>
            )}
          />
          <div style={{ height: "0.2rem" }}></div>
          <Pagination defaultCurrent={1} size="small" total={total}
            onChange={onShowSizeChange} current={current} pageSize={pagesize}
          />
        </div>
        <br />
        {JSON.parse(storage.preitem_bgd).type === "add"?(<div style={{ ...styles.linestyle, marginTop: '2vw'}}>
          <Button type="" style={{
            width: "90%", height: "1.8rem", backgroundColor: "#1145d7", color: "rgb(254,209,0)", 
            fontSize: "0.8rem", borderRadius: "0.3rem",margin:'1vh auto'
          }} onClick={handleupload}>  <Icon type="file-add" /> 提交 </Button >
        </div>):<></>}

      </div>
    </div>
  )
}

export default Mobile_cprk_form

var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `white`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "30vw", paddingTop: "3vw", backgroundSize: '100% 100%',
    position: "relative", fontSize: "0.89rem", textIndent: "1rem", fontWeight: "800", color: "white", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { padding: '2vw 2vw', textAlign: 'left', width: "15%", height: "10vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#c13738", fontSize: "3vw", borderRadius: "0.4rem", borderRadius: "0 0 0.5rem 0.5rem" },
  butmainstyle: { padding: '2vw 2vw', textAlign: 'left', width: "16%", height: "10vw", position: "absolute", right: "16%", top: "0%", backgroundColor: "#c13738", fontSize: "3vw", borderRadius: "0.4rem", borderRadius: "0 0 0.5rem 0.5rem" },
  butbackstyle: { padding: '2vw 2vw', textAlign: 'left', width: "23%", borderRadius: "0.4rem", backgroundColor: "#c13738", height: "10vw", position: "absolute", right: "32%", top: "0%", fontSize: "3vw", borderRadius: "0 0 0.5rem 0.5rem" },
  kshcontainer: {
    width: "100%", height: "90%", position: "absolute", top: "12vh", left: "0vw", backgroundColor: "white", color: "black",
    borderRadius: "10px",
  },
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },

}